const { select, note, text, spinner, group, isCancel, cancel } = require("@clack/prompts");
const path = require("path");
const { getSettings } = require("./settings");
const { Workbook } = require("exceljs");
const dayjs = require("dayjs");
const { getI18nTranslates } = require("../utils");

async function main() {
  const settings = await getSettings();
  const rows = [];
  const defaultFilename =
    settings.fileNameType === "date" ? dayjs().format(settings.exportFileName) : settings.exportFileName;

  const config = await group({
    type: () =>
      select({
        message: "导出模式",
        initialValue: "incomplete",
        options: [
          { value: "all", label: "全部导出", hint: "导出完整的翻译配置文件（包含所有已配置的翻译键值对）" },
          {
            value: "incomplete",
            label: "导出待补全项",
            hint: "导出需补充翻译的条目（仅包含至少有一个语种已翻译但存在未完成语种的条目）",
          },
          {
            value: "incomplete-all",
            label: "导出未完成项",
            hint: "导出所有翻译未完成的条目（包含存在任意语种未翻译的条目，无论是否部分完成）",
          },
          { value: "empty", label: "导出空白项", hint: "导出完全未翻译的条目（仅包含所有语种均为空值的翻译键）" },
        ],
      }),
    filename: () => text({ message: "文件名(无需添加文件后缀名)", placeholder: defaultFilename }),
  });
  
  if (isCancel(config)) {
    cancel("操作取消");
    process.exit(0);
  }

  const _filename = config.filename || defaultFilename;
  const spin = spinner();
  const parsed = path.parse(_filename);
  const filename = path.join(settings.exportDir, `${parsed.name}.${settings.fileType}`);

  spin.start("正在导出数据");

  const { languages, translates } = await getI18nTranslates(settings.languageDir);

  languages.sort((a, b) => {
    if (a.includes(settings.defaultLanguage)) return -1;
    if (b.includes(settings.defaultLanguage)) return 1;
    return 0;
  });

  for (const [key, value] of Object.entries(translates)) {
    const values = languages.map((item) => value[item]);
    const isTranslated = values.every(Boolean);
    if (config.type !== "all" && isTranslated) continue;
    if (config.type === "incomplete" && values.every((item) => !item)) continue;
    if (config.type === "empty" && values.some(Boolean)) continue;
    value.key = key;
    rows.push(value);
  }

  const workbook = new Workbook();
  const sheet = workbook.addWorksheet("Sheet", { views: [{ state: "frozen", xSplit: 1, ySplit: 1 }] });

  sheet.columns = ["key", ...languages].map((key) => ({
    key,
    header: key,
    width: 50,
    style: { alignment: { wrapText: true, vertical: "middle" } },
  }));
  sheet.addRows(rows);
  sheet.getRow(1).height = 30;
  sheet.getRow(1).eachCell((cell) => {
    cell.font = { bold: true };
    cell.alignment = { horizontal: "center", vertical: "middle" };
  });
  await workbook[settings.fileType].writeFile(filename);

  spin.stop("文件已导出完毕。");
  note(`File Path:\n${filename}`, "Success");
}

module.exports = { main };

/**
{
  test : {
    abc : {
      def: "张三",
      ghi: "李四"
    },
    mln: "王五"
  }
}

{
  test.abc.def: {zh: '张三',en:'zhangsan'},
  test.abc.ghi: {zh: '李四',en:'lisi'},
  test.mln:     {zh: '王五',en:'wangwu'},
}
------------------------------
key          | zh   | en
------------------------------
test.abc.def | 张三 | zhangsan
------------------------------
test.abc.ghi | 李四 | lisi
------------------------------
test.mln     | 王五 | wangwu
------------------------------
*/
